package com.luzhikun.upload_2;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;
import java.util.List;

public class FileUploadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//        System.out.println("吾问无为谓无无");
        // 1,判断请求是否为multipart请求
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new RuntimeException("当前请求不支持文件上传");
        }
        try {
            // 创建一个FileItem工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 创建文件上传核心组件
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 解析请求,获取所有的item
            List<FileItem> fileItems = upload.parseRequest(request);
            // 遍历item
            Iterator<FileItem> iterator = fileItems.iterator();
            while (iterator.hasNext()) {
                FileItem next = iterator.next();
                // 若next为表单普通项
                if (next.isFormField()) {
                    // 获取表单项名称
                    String fieldName = next.getFieldName();
                    // 获取表单项value
                    String fileValue = next.getString();
                    System.out.println(fieldName + "==" + fileValue);
                } else {
                    // 如果next为文件上传的数据
                    // 获取上传文件的原始名称
                    String fieldName = next.getFieldName();
                    // 获取一个输入流
                    InputStream inputStream = next.getInputStream();
                    // 获取文件保存在服务器的路径
                    String path = this.getServletContext().getRealPath("/images");
                    // 创建一个文件用来存放需要写出的数据
                    File descFile = new File(path, fieldName);
                    // 创建一个输出流（要有一个目标文件）
                    OutputStream os = new FileOutputStream(descFile);
                    // 将输入流中的数据写入到输出流
                    int len = -1;
                    byte[] bytes = new byte[1024];
                    while ((len = inputStream.read(bytes)) != -1) {
                        os.write(bytes, 0, len);
                    }
                    // 关闭流
                    os.close();
                    inputStream.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

